Text to Speech Web Tool Using HTML, CSS, and JavaScript

A complete guide to building a Text to Speech Web Tool with step-by-step instructions.

Text to Speech Tool

Introduction

Text to Speech (TTS) tools are used to convert written text into spoken words. In this tutorial, we will guide you through the steps of building a TTS Web Tool using HTML, CSS, and JavaScript.

Step 1: Set Up HTML Structure

First, we need to set up the basic HTML structure for the Text to Speech tool. Here's the code:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text to Speech Tool</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Text to Speech Tool</h1>
        <textarea id="textInput" placeholder="Enter your text here"></textarea>
        <button id="speakBtn">Speak</button>
    </div>
    <script src="script.js"></script>
</body>
</html>
                

Step 2: Styling with CSS

Now, let's style the Text to Speech tool with CSS:


* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
}

body {
    background-color: #f4f4f9;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.container {
    text-align: center;
    background: #ffffff;
    padding: 40px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

textarea {
    width: 100%;
    height: 150px;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
    border: 1px solid #ddd;
}

button {
    padding: 10px 20px;
    background-color: #e85c0d;
    color: #fff;
    border: none;
    cursor: pointer;
    border-radius: 5px;
    margin-top: 10px;
    width: 100%;
}
                

Step 3: Adding JavaScript Functionality

Next, let's add the JavaScript to handle the text-to-speech functionality:


document.getElementById('speakBtn').addEventListener('click', function() {
    const textInput = document.getElementById('textInput').value;

    if (textInput.trim() === "") {
        alert("Please enter some text.");
        return;
    }

    const speech = new SpeechSynthesisUtterance(textInput);
    window.speechSynthesis.speak(speech);
});